package com.study.thread.ThreadPool;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.thymeleaf.expression.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;

@Slf4j
@Getter
class MyTask implements Runnable {
    private String name;

    public MyTask(String name) {
        this.name = name;
    }
    
    @Override
    public void run() {
        try {
            long threadId = Thread.currentThread().getId();
            Long duration = (long) (Math.random() * 10);
            log.info("Doing a task during : {}, threadId={}，sleep:{}" ,  name , threadId, duration);
            TimeUnit.SECONDS.sleep(duration);
            log.info("done a task during : {}, threadId={}" , name , threadId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 5, 100, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(1), new ThreadPoolExecutor.DiscardPolicy());
        Callable<String> callable = () -> {
            //Thread.sleep(1_100);
            return "ok";
        };
        List<Future<String>> futureList = new ArrayList<>();
        IntStream.rangeClosed(1, 10).forEach(value -> {
            Future<String> future = threadPoolExecutor.submit(callable);
            futureList.add(future);
        });
        Thread.sleep(1_100);
        int i = 0;
        futureList.forEach(item->{
            try {
                System.out.println(item.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
        IntStream.rangeClosed(1, 10).forEach(value -> {
            try {
                System.out.println(value);
                System.out.println(futureList.get(value - 1).get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

//        Thread.sleep(10_000);
        threadPoolExecutor.shutdown();
    }

}

